//
//  YBNewChoosePeopleViewController.m
//  GongXinDangJian
//
//  Created by apple on 17/11/30.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YBNewChoosePeopleViewController.h"
#import "YBNormalSearchButton.h"
#import "YBWaterLayout.h"
#import "YBNormalWaterCollectionViewCell.h"
#define CELLID @"YBNormalWaterCollectionViewCell"
#import "ZJSqlit.h"
#import "YBPeopleInfoModel.h"
#import "YBSelectHeadModel.h"

#import "YBSelectPeopleOftenUseView.h"
#import "LCustomAlertView.h"

#import "YBSelectShareSingalData.h"
#import "YBSelectPeopleOrganizationView.h"

#import "YBAddCustomGroupViewController.h"

#import "YBSelectPeopleSearchViewController.h"

#import "YBNewSelectPeopleOfftenUseView.h"

@interface YBNewChoosePeopleViewController ()<UICollectionViewDelegate , UICollectionViewDataSource ,YBWaterLayoutDelegate , YBSelectPeopleOftenUseViewDelegate , LCustomAlertDelegate , YBSelectPeopleOrganizationViewDelegate , YBSelectPeopleSearchViewControllerDelegate , YBNewSelectPeopleOfftenUseViewDelegate>
@property (nonatomic , strong) YBNormalSearchButton * searchButton;

@property (nonatomic , strong) NSMutableArray * titleLineArray;

@property (nonatomic , strong) UIButton * selectButton;

@property (nonatomic , strong) UILabel * selectNumberLabel;

@property (nonatomic , strong) UICollectionView * collectionView;

@property (nonatomic , strong) YBSelectShareSingalData * myDataSource;

@property (nonatomic , strong) UIButton * sureButton;

@property (nonatomic , strong) YBNewSelectPeopleOfftenUseView * oftenUseView;

@property (nonatomic , strong) YBSelectPeopleOftenUseView * customGroupView;

@property (nonatomic , strong) YBSelectPeopleOrganizationView * organizationView;

@property (nonatomic , strong) ZJSqlit * mySqlite;

@property (nonatomic , strong) NSArray * oftenDeptArray;

@property (nonatomic , strong) NSArray * oftenUserArray;

@property (nonatomic , strong) NSArray * deptArray;

@property (nonatomic , strong) NSArray * userArray;

@property (strong, nonatomic) JCAlertView  *jcAlertView;

@property (nonatomic , assign) NSInteger currentDeleteIndex;


@end


@implementation YBNewChoosePeopleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentDeleteIndex = 0;
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        self.oftenDeptArray = [NSArray yy_modelArrayWithClass:[YBSelectHeadModel class] json:[self.mySqlite getStringById:YBUSERDATAKEY fromTable:@"ORG_OFTEN_DEPTS"]];
        self.oftenUserArray = [NSArray yy_modelArrayWithClass:[YBPeopleInfoModel class] json:[self.mySqlite getStringById:YBUSERDATAKEY fromTable:@"ORG_OFTEN_USERS"]];
    }
    else{
        self.oftenDeptArray = @[];
        self.oftenUserArray = @[];
    }
    YBSelectHeadModel * oftenUseTopModel = [[YBSelectHeadModel alloc]init];
    oftenUseTopModel.DATA_TYPE = @"0";
    oftenUseTopModel.DEPT_LV = @"1";
    oftenUseTopModel.FID = @"0";
    oftenUseTopModel.F_DEPT_NAME = @"";
    oftenUseTopModel.ID = @"000000";
    oftenUseTopModel.IS_COMMON = @"1";
    oftenUseTopModel.NAME = @"全部";
    
    NSMutableArray * tempArray = [self.oftenDeptArray mutableCopy];
    [tempArray addObject:oftenUseTopModel];
    self.oftenDeptArray = [tempArray copy];
    
    self.deptArray = [NSArray yy_modelArrayWithClass:[YBSelectHeadModel class] json:[self.mySqlite getStringById:YBUSERDATAKEY fromTable:@"ORG_DEPTS"]];
    self.userArray = [NSArray yy_modelArrayWithClass:[YBPeopleInfoModel class] json:[self.mySqlite getStringById:YBUSERDATAKEY fromTable:@"ORG_USERS"]];
    self.titlelabel.text = @"选择人员";
    self.titleLineArray = [NSMutableArray array];
    [self ybInitUserInterface];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.customGroupView.hidden) {
        [self ybInitCustomGroupView];
    }
}



-(void)dealloc
{
    if (self.oftenUseView) {
        [self.oftenUseView ybCleanObserver];
    }
    if (self.customGroupView) {
        [self.customGroupView ybCleanObserver];
    }
    if (self.organizationView) {
        [self.organizationView ybCleanObserver];
    }
    [YBSelectShareSingalData attempDealloc];
    self.myDataSource = nil;
}

-(void)ybInitUserInterface{
    [self.rightButton setImage:[UIImage imageNamed:@"custom_group_set"] forState:UIControlStateNormal];
    self.rightButton.hidden = YES;
    
    //头部视图
    UIView * headContentView = [[UIView alloc]initWithFrame:CGRectMake(0, navHeight, [UIScreen zj_screenWith], ItemHeight * 330)];
    headContentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headContentView];
    //搜索按钮
    [headContentView addSubview:self.searchButton];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, ItemHeight * 80 - 1 , [UIScreen zj_screenWith] , 1)];
    lineView.backgroundColor = [UIColor themeGrayColor];
    [headContentView addSubview:lineView];
    //标题按钮
    NSArray * titleArray;
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        titleArray = @[@"常用" , @"自定义分组" , @"组织机构"];
    }
    else{
        titleArray = @[@"自定义分组" , @"组织机构"];
    }
    for (int i = 0; i < titleArray.count; i ++) {
        UIButton * titleButton = [ToolClass createButtonWithFrame:CGRectMake([UIScreen zj_screenWith] / titleArray.count * i, ItemHeight * 80, [UIScreen zj_screenWith] / titleArray.count, ItemHeight * 80) text:titleArray[i] textColor:[UIColor textBlackColor] imageName:@"" font:16];
        titleButton.tag = 300 + i;
        [titleButton addTarget:self action:@selector(option_titleButton:) forControlEvents:UIControlEventTouchUpInside];
        [headContentView addSubview:titleButton];
        
        CGFloat titleWidth = [titleArray[i] boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : LYPFONT(16)} context:nil].size.width;
        
        UIView * titleLineView = [[UIView alloc]initWithFrame:CGRectMake([UIScreen zj_screenWith] / titleArray.count * i + ([UIScreen zj_screenWith] / titleArray.count - titleWidth) / 2, ItemHeight * 155 - 1, titleWidth, ItemHeight * 5)];
        titleLineView.backgroundColor = [UIColor themeColor];
        if (i == 0) {
            titleLineView.hidden = NO;
            [titleButton setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
            self.selectButton = titleButton;
        }
        else{
            titleLineView.hidden = YES;
        }
        [headContentView addSubview:titleLineView];
        [self.titleLineArray addObject:titleLineView];
    }
    
    UIView * lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, ItemHeight * 160 - 1, [UIScreen zj_screenWith], 1)];
    lineView2.backgroundColor = [UIColor themeGrayColor];
    [headContentView addSubview:lineView2];
    
    //结果展示视图
    [headContentView addSubview:self.selectNumberLabel];
    [headContentView addSubview:self.collectionView];
    
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, ItemHeight * 300, [UIScreen zj_screenWith], ItemHeight * 30)];
    bottomView.backgroundColor = [UIColor themeGrayColor];
    [headContentView addSubview:bottomView];
    
    
    //确定按钮
    [self.view addSubview:self.sureButton];
    
    [self.view addSubview:self.customGroupView];
    
    [self.view addSubview:self.organizationView];
    
//    [self ybInitDataSource];
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        [self.view addSubview:self.oftenUseView];
        [self.oftenUseView loadDataWithUserArray:self.oftenUserArray deptArray:self.oftenDeptArray];
    }
    else{
        self.rightButton.hidden = NO;
        self.customGroupView.hidden = NO;
        [self ybInitCustomGroupView];
    }
    
    [self.organizationView loadDataWithUserArray:self.userArray deptArray:self.deptArray];
    
    
    
}



-(void)ybInitCustomGroupView{
    [YBRequestManager request_customGroupListWithSuccessBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            NSArray * idArray = [self.myDataSource getCurrentSelectIdArray];
            NSArray * tempUserArray = [NSArray yy_modelArrayWithClass:[YBPeopleInfoModel class] json:object[@"ORG_MYSELF_DEPT_MEMBERS"]];
            NSArray * tempDeptArray = [NSArray yy_modelArrayWithClass:[YBSelectHeadModel class] json:object[@"ORG_MYSELF_DEPTS"]];
            
            NSMutableArray * oftenTotalUserArray = [NSMutableArray array];
            for (YBSelectHeadModel * model in tempDeptArray) {
                model.ISOPEN = NO;
                
                for (YBSelectHeadModel * deptModel in self.deptArray) {
                    if ([deptModel.ID isEqualToString:model.ID]) {
                        model.ISOPEN = deptModel.ISOPEN;
                    }
                }
                
                NSMutableArray * tempArray = [NSMutableArray array];
                NSInteger allCount = 0;
                for (YBPeopleInfoModel * peopleModel in tempUserArray) {
                    if ([model.ID isEqualToString:peopleModel.FID]) {
                        if ([idArray containsObject:peopleModel.ID]) {
                            peopleModel.ISSELECT = YES;
                            allCount ++;
                        }
                        else{
                            peopleModel.ISSELECT = NO;
                        }
                        [tempArray addObject:peopleModel];
                    }
                }
                if (allCount == tempArray.count) {
                    model.ISALLSELECT = YES;
                }
                else{
                    model.ISALLSELECT = NO;
                }
                [oftenTotalUserArray addObject:tempArray];
            }
            
            [self.customGroupView loadDataWithDataArray:oftenTotalUserArray headArray:[tempDeptArray mutableCopy]];
        }
    } failBlock:^(id object) {
        
    }];
}


//-(void)ybInitDataSource{
//    NSArray * idArray = [self.myDataSource getCurrentSelectIdArray];
//    NSMutableArray * oftenTotalUserArray = [NSMutableArray array];
//    for (YBSelectHeadModel * model in self.oftenDeptArray) {
//        model.ISOPEN = NO;
//        
//        NSMutableArray * tempArray = [NSMutableArray array];
//        NSInteger allCount = 0;
//        for (YBPeopleInfoModel * peopleModel in self.oftenUserArray) {
//            if ([model.ID isEqualToString:peopleModel.FID]) {
//                if ([idArray containsObject:model.ID]) {
//                    peopleModel.ISSELECT = YES;
//                    allCount ++;
//                }
//                else{
//                    peopleModel.ISSELECT = NO;
//                }
//                [tempArray addObject:peopleModel];
//            }
//        }
//        if (allCount == tempArray.count) {
//            model.ISALLSELECT = YES;
//        }
//        else{
//            model.ISALLSELECT = NO;
//        }
//        [oftenTotalUserArray addObject:tempArray];
//    }
//    
//    [self.oftenUseView loadDataWithDataArray:oftenTotalUserArray headArray:[self.oftenDeptArray mutableCopy]];
//}





-(void)option_titleButton:(UIButton *)sender{
    [self setSelectButtonWithButton:sender];
}


-(void)setSelectButtonWithButton:(UIButton * )button{
    NSInteger index = button.tag - 300;
    if (self.selectButton) {
        [self.selectButton setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
        UIView * lineView = self.titleLineArray[self.selectButton.tag - 300];
        lineView.hidden = YES;
    }
    [button setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
    UIView * theLineView = self.titleLineArray[index];
    theLineView.hidden = NO;
    self.selectButton = button;
    
    
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] != 2) {
        index ++;
    }
    
    
    if (index == 0) {
        self.rightButton.hidden = YES;
        self.oftenUseView.hidden = NO;
        self.customGroupView.hidden = YES;
        self.organizationView.hidden = YES;
    }
    else if (index == 1){
        self.rightButton.hidden = NO;
        self.oftenUseView.hidden = YES;
        self.customGroupView.hidden = NO;
        [self ybInitCustomGroupView];
        self.organizationView.hidden = YES;
    }else{
        self.rightButton.hidden = YES;
        self.oftenUseView.hidden = YES;
        self.customGroupView.hidden = YES;
        self.organizationView.hidden = NO;
    }
}


-(void)option_searchButton:(UIButton *)sender{
    //搜索按钮
    YBSelectPeopleSearchViewController * vc = [[YBSelectPeopleSearchViewController alloc]init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)option_ensureButton:(UIButton *)sender{
    //确定按钮
    if (self.delegate && [self.delegate respondsToSelector:@selector(ybClickEnsureButtonWithCurrentSelectArray:)]) {
        [self.delegate ybClickEnsureButtonWithCurrentSelectArray:[self.myDataSource.selectArray copy]];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)action_rightButton:(UIButton *)sender{
    YBAddCustomGroupViewController * addVC = [[YBAddCustomGroupViewController alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
}


-(void)option_flowLayoutCellDeleteButton:(UIButton *)sender{
    
    NSInteger index = sender.tag - 1000;
    self.currentDeleteIndex = index;
    YBPeopleInfoModel * tempModel = self.myDataSource.selectArray[index];
    LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:self.view.bounds alertMessage:[NSString stringWithFormat:@"是否删除 %@-%@" , [ToolClass returnNoNullStringWithString:tempModel.F_DEPT_NAME] , [ToolClass returnNoNullStringWithString:tempModel.NAME]] titlesArray:@[@"取消",@"确定"]];
    alert.delegate = self;
    self.jcAlertView = [[JCAlertView alloc]initWithCustomView:alert dismissWhenTouchedBackground:YES];
    [self.jcAlertView show];
}


-(void)YBSelectPeopleSearchViewControllerDidSelectPeopleModel:(YBPeopleInfoModel *)model
{
    [self.myDataSource ybAddObjectToArrayWithModel:model];
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        [self.oftenUseView ybReloadData];
    }
    [self.oftenUseView ybReloadData];
    [self.customGroupView ybReloadData];
    [self.organizationView ybReloadData];
    [self.collectionView reloadData];
    self.selectNumberLabel.text = [NSString stringWithFormat:@"已选择(%ld人):" , self.myDataSource.selectArray.count];
}



-(void)selectedArrayDidChange
{
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        if (self.oftenUseView.hidden) {
            [self.oftenUseView ybReloadData];
        }
    }
    if (self.customGroupView.hidden) {
        [self.customGroupView ybReloadData];
    }
    if (self.organizationView.hidden) {
        [self.organizationView ybReloadData];
    }
    [self.collectionView reloadData];
    self.selectNumberLabel.text = [NSString stringWithFormat:@"已选择(%ld人):" , self.myDataSource.selectArray.count];
}


-(void)ybSelectPeopleOrganizationViewSelectedArrayDidChange
{
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        if (self.oftenUseView.hidden) {
            [self.oftenUseView ybReloadData];
        }
    }
    if (self.customGroupView.hidden) {
        [self.customGroupView ybReloadData];
    }
    if (self.organizationView.hidden) {
        [self.organizationView ybReloadData];
    }
    [self.collectionView reloadData];
    self.selectNumberLabel.text = [NSString stringWithFormat:@"已选择(%ld人):" , self.myDataSource.selectArray.count];
}


-(void)ybNewSelectPeopleOfftenUseViewSelectedArrayDidChange
{
    if ([ZJUSERINFORMODEL.ORG_ACCOUNT.ISWORK integerValue] == 2) {
        if (self.oftenUseView.hidden) {
            [self.oftenUseView ybReloadData];
        }
    }
    if (self.customGroupView.hidden) {
        [self.customGroupView ybReloadData];
    }
    if (self.organizationView.hidden) {
        [self.organizationView ybReloadData];
    }
    [self.collectionView reloadData];
    self.selectNumberLabel.text = [NSString stringWithFormat:@"已选择(%ld人):" , self.myDataSource.selectArray.count];
}


#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (index == 1) {
        /**  确认  */
        YBPeopleInfoModel * tempModel = self.myDataSource.selectArray[self.currentDeleteIndex];
        tempModel.ISSELECT = NO;
        [self.myDataSource ybRemoveObjectFromArrayWithModel:tempModel];
        [self.collectionView reloadData];
        [self.oftenUseView ybReloadData];
        [self.customGroupView ybReloadData];
        [self.organizationView ybReloadData];
        self.selectNumberLabel.text = [NSString stringWithFormat:@"已选择(%ld人):" , self.myDataSource.selectArray.count];
        
    }
    [self.jcAlertView dismissWithCompletion:nil];
}



-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.myDataSource.selectArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBNormalWaterCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID forIndexPath:indexPath];
    cell.isSelectVC = YES;
    cell.model = self.myDataSource.selectArray[indexPath.row];
    cell.deleteButton.tag = 1000 + indexPath.row;
    [cell.deleteButton addTarget:self action:@selector(option_flowLayoutCellDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}


-(CGFloat)WaterfallFlowLayout:(YBWaterLayout *)layout widthForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBPeopleInfoModel * model = self.myDataSource.selectArray[indexPath.row];
    return model.selectNameWidth + ItemWidth * 60;
}




-(YBNormalSearchButton *)searchButton
{
    if (!_searchButton) {
        _searchButton = [[YBNormalSearchButton alloc]initWithFrame:CGRectMake(ItemWidth * 100, ItemHeight * 10, [UIScreen zj_screenWith] - ItemWidth * 200, ItemHeight * 60) title:@"输入关键字快速查询内容" imageName:@"soso" imageSize:ItemWidth * 40];
        [_searchButton addTarget:self action:@selector(option_searchButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}


-(UILabel *)selectNumberLabel
{
    if (!_selectNumberLabel) {
        _selectNumberLabel = [ToolClass creatLabelWithFrame:CGRectMake(0, ItemHeight * 160, ItemWidth * 220, ItemHeight * 80) font:15 textColor:[UIColor textGrayColor] text:@"已选择(0人):"];
        _selectNumberLabel.textAlignment = NSTextAlignmentRight;
    }
    return _selectNumberLabel;
}

-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        YBWaterLayout * layout = [[YBWaterLayout alloc]init];
        layout.minimumLineSpacing = ItemHeight * 1;
        layout.minimumInteritemSpacing = ItemWidth * 10;
        layout.sectionInset = UIEdgeInsetsMake(0, ItemWidth * 10, 0 , ItemWidth * 10);
        layout.itemHeight = 75 * ItemHeight;
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(ItemWidth * 220, ItemHeight * 160, [UIScreen zj_screenWith] - ItemWidth * 220, ItemHeight * 140) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[YBNormalWaterCollectionViewCell class] forCellWithReuseIdentifier:CELLID];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.allowsSelection = NO;
    }
    return _collectionView;
}



-(UIButton *)sureButton
{
    if (!_sureButton) {
        _sureButton = [ToolClass createButtonWithFrame:CGRectMake(0, [UIScreen zj_screenHeight] - ItemHeight * 100, [UIScreen zj_screenWith], ItemHeight * 100) text:@"确定" textColor:[UIColor whiteColor] imageName:@"" font:16];
        _sureButton.backgroundColor = [UIColor themeColor];
        [_sureButton addTarget:self action:@selector(option_ensureButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureButton;
}


-(YBNewSelectPeopleOfftenUseView *)oftenUseView
{
    if (!_oftenUseView) {
        _oftenUseView = [[YBNewSelectPeopleOfftenUseView alloc]initWithFrame:CGRectMake(0, ItemHeight * 330 + navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - ItemHeight * 430 - navHeight)];
        _oftenUseView.delegate = self;
    }
    return _oftenUseView;
}


-(YBSelectPeopleOftenUseView *)customGroupView
{
    if (!_customGroupView) {
        _customGroupView = [[YBSelectPeopleOftenUseView alloc]initWithFrame:CGRectMake(0, ItemHeight * 330 + navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - ItemHeight * 430 - navHeight)];
        _customGroupView.delegate = self;
        _customGroupView.hidden = YES;
    }
    return _customGroupView;
}

-(YBSelectPeopleOrganizationView *)organizationView
{
    if (!_organizationView) {
        _organizationView = [[YBSelectPeopleOrganizationView alloc]initWithFrame:CGRectMake(0, ItemHeight * 330 + navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - ItemHeight * 430 - navHeight)];
        _organizationView.delegate = self;
        _organizationView.hidden = YES;
    }
    return _organizationView;
}





-(ZJSqlit *)mySqlite
{
    if (!_mySqlite) {
        _mySqlite = [[ZJSqlit alloc]init];
    }
    return _mySqlite;
}


-(YBSelectShareSingalData *)myDataSource
{
    if (!_myDataSource) {
        _myDataSource = [YBSelectShareSingalData getYBSelectShareSingalData];
    }
    return _myDataSource;
}


@end
